// pages/address/address.js
import {
  throttle
} from '../../utils/util'
import api from '../../utils/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEmpty: true,
    list: []
  },

  myAddressList () {
    api.myAddressList({
      data: {},
      success: res => {
        if (res.code * 1 === 0) {
          console.log(res, 'res====================')
          if (res.data.length * 1 === 0) {
            this.setData({
              isEmpty: true,
              list: []
            })
          } else {
            this.setData({
              list: res.data,
              isEmpty: false
            })
          }
        }
      }
    })
  },

  addressDelete (e) {
    let id = e.target.dataset.id
    api.addressDelete({
      data: {
        addressId: id
      },
      success: res => {
        if (res.code * 1 === 0) {
          this.myAddressList()
        } else {
          wx.showToast({
            title: res.msg
          })
        }
      }
    })
  },

  switch1Change(e) {
    let id = e.target.dataset.id
    api.addressSsetDefault({
      data: {
        addressId: id
      },
      success: res => {
        if (res.code * 1 === 0) {
          this.myAddressList()
        } else {
          wx.showToast({
            title: res.msg
          })
        }
      }
    })
  },
  addressEdit (e) {
    let item = e.target.dataset.item
    wx.setStorageSync('addressEditItem', item)
    throttle(function (e) {
      wx.navigateTo({
        url: '../addAddress/addAddress'
      })
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.myAddressList()
    wx.removeStorageSync('addressEditItem')
  },

  addAddress () {
    wx.removeStorageSync('addressEditItem')
    throttle(function (e) {
      wx.navigateTo({
        url: '../addAddress/addAddress'
      })
    }, 2000)
  }
})